﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.UI;
using Entity.CommonEnums;

namespace Web.Helper
{
    /// <summary>
    /// HTML扩展类型
    /// </summary>
    public static class HtmlExtensions
    {
        #region RequestContext 扩展

        public static bool IsCurrentRoute(this RequestContext context, String areaName)
        {
            return context.IsCurrentRoute(areaName, null, null);
        }

        public static bool IsCurrentRoute(this RequestContext context, String areaName, String controllerName)
        {
            return context.IsCurrentRoute(areaName, controllerName, null);
        }

        /// <summary>
        /// 是否为当前路由（传入的URL与当前URL是否相同）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="areaName"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionNames"></param>
        /// <returns></returns>
        public static bool IsCurrentRoute(this RequestContext context, String areaName, String controllerName, params String[] actionNames)
        {
            var routeData = context.RouteData;
            var routeArea = routeData.DataTokens["area"] as String;
            var current = false;

            if (!(((String.IsNullOrEmpty(routeArea) && String.IsNullOrEmpty(areaName)) || (routeArea == areaName)) &&
                 ((String.IsNullOrEmpty(controllerName)) || (routeData.GetRequiredString("controller") == controllerName)) &&
                 ((actionNames == null) || actionNames.Contains(routeData.GetRequiredString("action")))))
            {
                current = true;
            }

            return current;
        }

        #endregion RequestContext 扩展

        #region UrlHelper 扩展

        public static bool IsCurrent(this UrlHelper urlHelper, String areaName)
        {
            return urlHelper.IsCurrent(areaName, null, null);
        }

        public static bool IsCurrent(this UrlHelper urlHelper, String areaName, String controllerName)
        {
            return urlHelper.IsCurrent(areaName, controllerName, null);
        }

        public static bool IsCurrent(this UrlHelper urlHelper, String areaName, String controllerName, params String[] actionNames)
        {
            return urlHelper.RequestContext.IsCurrentRoute(areaName, controllerName, actionNames);
        }

        public static string Selected(this UrlHelper urlHelper, String areaName)
        {
            return urlHelper.Selected(areaName, null, null);
        }

        public static string Selected(this UrlHelper urlHelper, String areaName, String controllerName)
        {
            return urlHelper.Selected(areaName, controllerName, null);
        }

        public static string Selected(this UrlHelper urlHelper, String areaName, String controllerName, params String[] actionNames)
        {
            return urlHelper.IsCurrent(areaName, controllerName, actionNames) ? "selected" : String.Empty;
        }

        #endregion UrlHelper 扩展

        #region HtmlHelper 扩展

        /// <summary>
        /// 添加导航菜单（当前URL相同是select样式，返回去除select样式）
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="linkText"></param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName)
        {
            var tag = new TagBuilder("li");
            if (htmlHelper.ViewContext.RequestContext.IsCurrentRoute(null, controllerName, actionName))
            {
                tag.AddCssClass("selected");
            }
            tag.InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToString();
            return MvcHtmlString.Create(tag.ToString());
        }

        #endregion HtmlHelper 扩展

        #region PartialView扩展

        /// <summary>
        /// 将指定ascx分部视图的文本内容追加到当前输出流
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="partial">ascx路径</param>
        /// <returns></returns>
        public static string RenderPartialToString(this HtmlHelper htmlHelper, string partial)
        {
            var viewInstance = BuildManager.CreateInstanceFromVirtualPath(partial, typeof(object));
            var control = viewInstance as ViewUserControl;
            control.ViewContext = htmlHelper.ViewContext;
            control.ViewData = htmlHelper.ViewData;
            Page page = new ViewPage();
            page.Controls.Add(control);
            TextWriter writer = new StringWriter();
            htmlHelper.ViewContext.HttpContext.Server.Execute(page, writer, false);
            return writer.ToString();
        }

        /// <summary>
        /// 返回指定ascx分部视图的文本内容
        /// 如果在页面上输出解释后的ＨＴＭＬ，请使用Html.Decode()
        /// </summary>
        /// <param name="partial">ascx路径</param>
        /// <param name="model">视图模型数据</param>
        /// <returns></returns>
        public static string RenderPartialToString(string partial, object model)
        {
            ViewDataDictionary vd = new ViewDataDictionary(model);
            ViewPage viewPage = new ViewPage { ViewData = vd };
            Control control = viewPage.LoadControl(partial);
            viewPage.Controls.Add(control);
            StringBuilder str = new StringBuilder();
            using (StringWriter stringWriter = new StringWriter(str))
            {
                using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter))
                {
                    viewPage.RenderControl(htmlTextWriter);
                }
            }
            return str.ToString();
        }

        /// <summary>
        ///  返回指定ascx分部视图的文本内容
        /// </summary>
        /// <param name="partial">ascx路径</param>
        /// <returns></returns>
        public static string RenderPartialToString(string partial)
        {
            return RenderPartialToString(partial, null);
        }

        #endregion PartialView扩展

        #region 按钮的扩展

        /// <summary>
        /// 按钮对象，只产生按钮，对按钮的click等事件需要在具体页面自己添加
        /// </summary>
        /// <param name="html"></param>
        /// <param name="buttonName">按钮ID</param>
        /// <param name="displayName">按钮显示名称</param>
        /// <param name="userOperatorRole">按钮权限</param>
        /// <param name="buttonType">按钮类型</param>
        /// <returns></returns>
        public static MvcHtmlString CreateButton(this HtmlHelper html, string buttonName, string displayName, UserOperatorRole userOperatorRole, ButtonType buttonType)
        {
            var tag = new TagBuilder("input");
            tag.AddCssClass("button");
            tag.Attributes["Name"] = buttonName;
            tag.Attributes["ID"] = buttonName;
            tag.Attributes["Value"] = displayName;
            tag.Attributes["Type"] = buttonType.ToString();

            //if ((Tsingda.XXB.Common.WebSession.UserOperatorRole & userOperatorRole) == 0)
            //{
            //    tag.Attributes["disabled"] = "disabled";
            //    tag.AddCssClass("button gray");
            //}
            return MvcHtmlString.Create(tag.ToString());
        }

        /// <summary>
        /// 按钮对象，只产生按钮，对按钮的click等事件需要在具体页面自己添加
        /// ID默认为button
        /// </summary>
        /// <param name="html"></param>
        /// <param name="userOperatorRole">按钮权限</param>
        /// <returns></returns>
        public static MvcHtmlString CreateButton(this HtmlHelper html, UserOperatorRole userOperatorRole, ButtonType buttonType)
        {
            return CreateButton(html, "Button", "提交", userOperatorRole, buttonType);
        }

        /// <summary>
        /// 按钮对象，只产生按钮，对按钮的click等事件需要在具体页面自己添加
        /// ID默认为button
        /// 按钮类型为Submit
        /// </summary>
        /// <param name="html"></param>
        /// <param name="userOperatorRole"></param>
        /// <returns></returns>
        public static MvcHtmlString CreateButton(this HtmlHelper html, UserOperatorRole userOperatorRole)
        {
            return CreateButton(html, "Button", "提交", userOperatorRole, ButtonType.Submit);
        }

        /// <summary>
        /// 按钮对象，只产生按钮，对按钮的click等事件需要在具体页面自己添加
        /// </summary>
        /// <param name="html"></param>
        /// <param name="buttonName">按钮ID</param>
        /// <param name="userOperatorRole">按钮权限</param>
        /// <param name="buttonType">按钮类型</param>
        /// <returns></returns>
        public static MvcHtmlString CreateButton(this HtmlHelper html, string buttonName, UserOperatorRole userOperatorRole, ButtonType buttonType)
        {
            return CreateButton(html, buttonName, "提交", userOperatorRole, buttonType);
        }

        /// <summary>
        /// 按钮对象，只产生按钮，对按钮的click等事件需要在具体页面自己添加
        /// 按钮类型为Submit
        /// </summary>
        /// <param name="html"></param>
        /// <param name="buttonName">按钮ID</param>
        /// <param name="userOperatorRole">按钮权限</param>
        /// <returns></returns>
        public static MvcHtmlString CreateButton(this HtmlHelper html, string buttonName, UserOperatorRole userOperatorRole)
        {
            return CreateButton(html, buttonName, "提交", userOperatorRole, ButtonType.Submit);
        }

        #endregion 按钮的扩展
    }
}